﻿using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
namespace CxExtension
{
	public static class ObjectExtension
	{
		public static BindingFlags default_flags = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance;
		/// <summary>
		/// 设置某个名字的属性
		/// </summary>
		/// <param name="self"></param>
		/// <param name="propertyName"></param>
		/// <param name="value"></param>
		/// <param name="flags"></param>
		public static void SetProperty(this object self,string propertyName,string value,BindingFlags flags = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance)
		{
			Type type = self.GetType();
			var property = type.GetProperty(propertyName,flags);
			if(property == null)
				return;
			var pro_type = property.PropertyType;
			var value1 = value.ParseValue(pro_type);
			property.SetValue(self,value1,null);
		}
		public static void SetValue(this object self,Dictionary<string,string> map)
		{
			foreach(var item in map)
			{
				try
				{
					self.SetProperty(item.Key,item.Value);
				}
				catch(Exception e)
				{
					Debug.LogErrorFormat("读取配置失败 class = {0},id = {3},key = {1},value = {2}",self.GetType().Name,item.Key,item.Value,map["id"]);
					throw e;
				}
			}
		}
	}
}